package com.app.serial.utils;/**
 * @program: app-admin
 * @name HexByteUtil
 * @description:
 */

import com.app.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;

/**
 *@author:
 *@program: app-admin
 *@name HexByteUtil
 *@description: 十六进制和byte进行转换
 */
@Slf4j
public class HexByteUtil {

    /**
     * 字节转十六进制
     * @param b 需要进行转换的byte字节
     * @return  转换后的Hex字符串
     */
    public static String byteToHex(byte b){
        String hex = Integer.toHexString(b & 0xFF);
        if(hex.length() < 2){
            hex = "0" + hex;
        }
        return hex;
    }


    /**
     * Hex字符串转byte
     * @param inHex 待转换的Hex字符串
     * @return  转换后的byte
     */
    public static byte hexToByte(String inHex){
        return (byte)Integer.parseInt(inHex,16);
    }

    /**
     * 字节数组转16进制
     * @param bytes 需要转换的byte数组
     * @return  转换后的Hex字符串
     */
    public static String bytesToHex(byte[] bytes) {
        StringBuffer sb = new StringBuffer();
        for(int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(bytes[i] & 0xFF);
            if(hex.length() < 2){
                sb.append(0);
            }
            sb.append(hex);
        }
        return sb.toString().toUpperCase();
    }

    /**
     * hex字符串转byte数组
     * @param inHex 待转换的Hex字符串
     * @return  转换后的byte数组结果
     */
    public static byte[] hexToByteArray(String inHex){
        int hexlen = inHex.length();
        byte[] result;
        if (hexlen % 2 == 1){
            //奇数
            hexlen++;
            result = new byte[(hexlen/2)];
            inHex="0"+inHex;
        }else {
            //偶数
            result = new byte[(hexlen/2)];
        }
        int j=0;
        for (int i = 0; i < hexlen; i+=2){
            result[j]=hexToByte(inHex.substring(i,i+2));
            j++;
        }
        return result;
    }

    /**
     *功能描述 int 转16进制
     * @author lizhi
     * @date 2020/4/28
     * @param n:
     * @return java.lang.String
     */
    public static String intToHex(int n){
        String string = Integer.toHexString(n).toUpperCase();
        return StringUtils.leftPad(string, 2, "0");
    }

    /**
     *功能描述 16进制转int
     * @author lizhi
     * @date 2020/4/28
     * @param hex:
     * @return int
     */
    public static int hexToInt(String hex){
        return Integer.parseInt(hex, 16);
    }


    public static float bytesToFloat(byte[] b) {
        int accum = 0;
        accum = accum|(b[0] & 0xff) << 0;
        accum = accum|(b[1] & 0xff) << 8;
        accum = accum|(b[2] & 0xff) << 16;
        accum = accum|(b[3] & 0xff) << 24;
        return Float.intBitsToFloat(accum);
    }


    public static void main(String[] args) {
        byte[] bytes = new byte[1];
        bytes[0] = 0X09;
        System.out.println(bytesToHex(bytes));

    }

}
